﻿/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#include "JistCommonDelegate.h"
#include "JistCommonModel.h"
#include <QLineEdit>"

int JistCommonDelegate::m_PixelSize = 40;

JistCommonDelegate::JistCommonDelegate(QObject *parent)
    : QItemDelegate(parent)
    ,m_MyCheckBoxEditor(NULL)
//    ,m_PixelSize(40)
{
    //setCheckBoxVisible(true);
    m_bCheckBoxVisible = true;
}


void JistCommonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // 이미지 그리기
    QImage img;
    if (1)//qVariantValue<QString>(index.model()->data(index, Qt::DisplayRole)).isEmpty() ||
          //  !qVariantValue<QImage>(index.model()->data(index, Qt::UserRole+2)).isNull())
    {
        //QItemDelegate::paint(painter, option, index);
        //img = v.value< QImage>((QVariant &)(index.model()->data(index, Qt::UserRole+2)));
         qDebug("JistCommonDelegate::paint");
        QVariant v;
        v.setValue((index.model()->data(index, Qt::UserRole+2)));
        img = v.value<QImage>();

        //bool value = index.data(Qt::CheckStateRole).toBool();
        QString text = index.data(Qt::DisplayRole).toString();
        int UIOption = index.data(Qt::UserRole + 3).toInt();

        // 선택된 열 배경 파란색
        if (option.state & QStyle::State_Selected)
            painter->fillRect(option.rect, QColor(0,0,255,50));
        if(!img.isNull())
            painter->fillRect(m_PixelSize*2, option.rect.y(), m_PixelSize, m_PixelSize, QColor(83,83,83));

        //QImage *qi = new QImage(QString(":/images/side2.png"));
        //double radius = (size/2.0) - (brightness/255.0 * size/2.0);
        //if (radius == 0.0)
        //    return;

        painter->save();
        painter->setOpacity(1.0f);

        //painter->setOpacity(0.1f);
        painter->setRenderHint(QPainter::Antialiasing, true);
        painter->setPen(Qt::SolidLine);

//        if (option.state & QStyle::State_Selected)
//            painter->setPen(QColor(200,100,50));//painter->setBrush(option.palette.highlightedText());
//        else
//            painter->setBrush(option.palette.text());
    //    painter->drawEllipse(QRectF(option.rect.x() + option.rect.width()/2 - radius,
    //                                option.rect.y() + option.rect.height()/2 - radius,
    //                                2*radius, 2*radius));
        //painter->setBrush(option.palette.text());
        int size = qMin(option.rect.width(), option.rect.height());
        //painter->setPen(Qt::SolidLine);
        // 열의 숫자 표시
        //QString name = index.model()->data(index, Qt::DisplayRole).toString();
        //painter->drawText(QRectF(option.rect.x() + 30, option.rect.height() - 15, option.rect.width(), 15), Qt::AlignVCenter,  name);
        //if(text.isEmpty())
        painter->drawText(QRectF(option.rect.x() - 10, option.rect.y(), size, size), Qt::AlignVCenter | Qt::AlignRight,  QString::number(index.row()));

        QImage  simage = img.scaled(QSize(m_PixelSize, m_PixelSize), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        painter->drawImage(m_PixelSize*2, option.rect.y(), simage);//, rect.x(), rect.y(), rect.width(), rect.height());

        if(UIOption != 0 ){
            QImage optImg = QImage(tr(":/images/24x24/document-properties.png"));
            painter->drawImage(m_PixelSize*3, option.rect.y(), optImg);//, rect.x(), rect.y(), rect.width(), rect.height());
        }
       // int subCnt = qVariantValue<int>(index.model()->data(index, Qt::UserRole+4));
        //QVariant v;
        v.setValue(index.model()->data(index, Qt::UserRole+4));
        int subCnt = v.value<int>();

        if(subCnt){
            //QString(QLatin1String("[%1, %2, %3 (%4 * %5)]" )).arg(p.x()).arg(p.y()).arg(z).arg(r.width()).arg(r.height())
            QString cntStr = QString(QLatin1String("%1 [%2]" )).arg(text).arg(subCnt);
            painter->setPen(QColor(255,255,255));
            painter->drawText(QRectF(option.rect.x() + 36, option.rect.y() + 1, size*8, size), Qt::AlignVCenter | Qt::AlignLeft, cntStr);
            painter->setPen(QColor(0,0,0));
            painter->drawText(QRectF(option.rect.x() + 35, option.rect.y(), size*8, size), Qt::AlignVCenter | Qt::AlignLeft, cntStr);
        }
        else{
            painter->setPen(QColor(255,255,255));
            painter->drawText(QRectF(option.rect.x() + 36, option.rect.y() + 1, size*8, size), Qt::AlignVCenter | Qt::AlignLeft, text);
            painter->setPen(QColor(0,0,0));
            painter->drawText(QRectF(option.rect.x() + 35, option.rect.y(), size*8, size), Qt::AlignVCenter | Qt::AlignLeft, text);
        }



      // fill style options with item data
    /*

        QPushButton *myEditor = new QPushButton((QWidget*)parent());
        const QStyle *style = QApplication::style();
        QStyleOptionButton opt;
        //opt.state |= QStyle::State_On;
        opt.state |= QStyle::State_Enabled;
        //opt.text = text;
        opt.rect = QRect(option.rect.x(), option.rect.y(), 20,20);
        style->drawControl(QStyle::CE_PushButton,&opt,painter, myEditor);
        //drawCheck(painter, option,option.rect, Qt::Checked);
    */
        painter->restore();
    }
    else {
        QItemDelegate::paint(painter, option, index);
        // 선택된 열 배경 파란색
        if (option.state & QStyle::State_Selected)
            painter->fillRect(option.rect, QColor(0,0,255,50));

        painter->save();
        painter->setOpacity(1.0f);

        painter->setRenderHint(QPainter::Antialiasing, true);
        painter->setPen(Qt::SolidLine);

        if (option.state & QStyle::State_Selected)
            painter->setBrush(option.palette.highlightedText());
        else
            painter->setBrush(option.palette.text());
        painter->restore();
   }

}

QSize JistCommonDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (1)//qVariantValue<QString>(index.model()->data(index, Qt::DisplayRole)).isEmpty())
    {
        return QSize(m_PixelSize*10, m_PixelSize);
    } else {
        return QItemDelegate::sizeHint(option, index);
    }
}

void JistCommonDelegate::setPixelSize(int size)
{
    m_PixelSize = size;
}


QWidget *JistCommonDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & option , const QModelIndex & index ) const
{
//    QPushButton *myEditor = new QPushButton(parent);
//    //myEditor->setIcon(QIcon(QPixmap (40, 40)));
//    //myEditor->setFixedSize(QSize(40,30));
//    //myEditor->setBaseSize(200,40);
//    myEditor->setAutoFillBackground(false);
//    myEditor->setContentsMargins(10,10,10,10);
//    QRect rect = index.model()->data(index, Qt::UserRole).toRect();
//    QImage  cutImage = m_Img.copy(rect);
//    QImage  simage = cutImage.scaled(QSize(m_PixelSize, m_PixelSize), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
//    myEditor->setIcon(QIcon(QPixmap::fromImage(simage)));
//    myEditor->setIconSize(QSize(m_PixelSize,m_PixelSize));

//    return myEditor;

    if (1)//qVariantValue<QString>(index.model()->data(index, Qt::DisplayRole)).isEmpty() &&
          //    !qVariantValue<QImage>(index.model()->data(index, Qt::UserRole+2)).isNull())
    {
        // create check box as our editor
        QCheckBox *myEditor = new QCheckBox(parent);
        QVariant v;
        v.setValue(index.model()->data(index, Qt::UserRole+2));
        QImage img = v.value<QImage>();
        v.setValue(index.model()->data(index, Qt::DisplayRole));
        QString str = v.value<QString>();
        if(img.isNull()
           && !str.isEmpty()){
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
            QString localeStr = codec->toUnicode("누적선택");
            myEditor->setToolTip(localeStr);
        }
        //QString text = index.data(Qt::DisplayRole).toString();
        //myEditor->setText(text);
        // myEditor->setVisible(false);
        connect(myEditor, SIGNAL(released()), this, SLOT(setFocus()));
        connect(myEditor, SIGNAL(clicked(bool)), this, SLOT(setCheckBoxVisible(bool)));

        return myEditor;
    }
    else {
        // create check box as our editor
       QLineEdit *myEditor = new QLineEdit(parent);
        // myEditor->setVisible(false);
        //myEditor->setWindowOpacity(0.5);
        return myEditor;
    }

}

void JistCommonDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
//    QPushButton *myEditor = static_cast<QPushButton*>(editor);
//    myEditor->setText(QString("add"));
//    index.data(Qt::UserRole + 1).toBool();
    if (1)//qVariantValue<QString>(index.model()->data(index, Qt::DisplayRole)).isEmpty() &&
          //    !qVariantValue<QImage>(index.model()->data(index, Qt::UserRole+2)).isNull())
    {
        //set editor data
        QCheckBox *myEditor = static_cast<QCheckBox*>(editor);
        myEditor->setChecked(index.data(Qt::UserRole + 1).toBool());
        //myEditor->setText(index.data(Qt::DisplayRole).toString());
    }
    else {
        //set editor data
        QLineEdit *myEditor = static_cast<QLineEdit*>(editor);
        myEditor->setText(index.data(Qt::DisplayRole).toString());
        myEditor->setBackgroundRole(QPalette::Button);
    }
}

void JistCommonDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QMap<int,QVariant> data;
    QVariant v;
    v.setValue(index.model()->data(index, Qt::DisplayRole));
    QString tempStr = v.value<QString>();
    if (1)//qVariantValue<QString>(index.model()->data(index, Qt::DisplayRole)).isEmpty() &&
          //    !qVariantValue<QImage>(index.model()->data(index, Qt::UserRole+2)).isNull())
    {
    //    //get the value from the editor (CheckBox)
    //    QPushButton *myEditor = static_cast<QPushButton*>(editor);
    //    value = myEditor->isEnabled();

    //    //set model data

    //    //data.insert(Qt::DisplayRole,myEditor->text());
    //    data.insert(Qt::UserRole + 1,value);
    //    model->setItemData(index,data);

        if(m_bCheckBoxVisible)
        {
            bool value = false;
            //get the value from the editor (CheckBox)
            QCheckBox *myEditor = static_cast<QCheckBox*>(editor);
            value = myEditor->isChecked();
            //set model data

            //data.insert(Qt::DisplayRole,myEditor->text());
            data.insert(Qt::UserRole + 1,value);
            JistCommonModel *m = (JistCommonModel*)model;
            // 셀 비져블 관리
            int curIndex = index.row();
            if(m->m_pList->at(curIndex).m_pIItem && m->m_pList->at(curIndex).m_pIItem->isVisible() != value){
                JistTableView* table = (JistTableView*)parent();
                table->selectRow(index.row());
            }

            model->setItemData(index,data);
            //myEditor->setVisible(false);
        }
    }
    // 스프라이트가 삭제되었을때 셀리스트를 클릭하면 이미지가 삭제되어 라인에디터를 편집하게 되지만
    // 최초에 생성된 에디터는 체크박스 에디터라서 런타임버그 발생 => 삭제되면 라인에디터 분기 진입을 막음
    else if(!tempStr.isEmpty()){
        QString value;
        //get the value from the editor (CheckBox)
        QLineEdit *myEditor = static_cast<QLineEdit*>(editor);
        value = myEditor->text();
        //set model data

        //data.insert(Qt::DisplayRole,myEditor->text());
        data.insert(Qt::DisplayRole,value);
        model->setItemData(index,data);
    }

}


void JistCommonDelegate::setImage(QImage img)
{
    m_Img = img.convertToFormat(QImage::Format_ARGB32);
}
void JistCommonDelegate::setFocus()
{
    JistTableView* table = (JistTableView*)parent();
    table->setFocus();

}

void JistCommonDelegate::setCheckBoxVisible(bool isVisible)
{
//    m_bCheckBoxVisible = isVisible;
    JistTableView* table = (JistTableView*)parent();
    int curIndex = table->currentIndex().row();
    JistCommonModel *m = (JistCommonModel*)table->model();

    if(curIndex >= 0 && m->m_pList->at(curIndex).m_pIItem){

        m->m_pList->at(curIndex).m_pIItem->setVisible(isVisible);
    }
}
